<?php
/**
 * Service of Metadata
 *
 * @author fusq
 */

require_once BaseUtil::getModulePath ( "base" ) . '/services/BaseService.php';
require_once BaseUtil::getModulePath ( 'dbgrid' ) . '/DBGrid.php';
require_once BaseUtil::getModulePath ( "metadata" ) . '/models/MetadataSetDao.php';
require_once BaseUtil::getModulePath ( "metadata" ) . '/models/MetadataGroupDao.php';
require_once BaseUtil::getModulePath ( "metadata" ) . '/models/MetadataDao.php';
require_once BaseUtil::getModulePath ( "metadata" ) . '/models/MetadataOptionDao.php';
require_once BaseUtil::getModulePath ( "metadata" ) . '/models/ColorDao.php';
require_once BaseUtil::getModulePath("systemlog")  .  '/services/SystemLogService.php';

class SetService extends BaseService {
	/**
	 * @var MetadataGroupDao
	 */
	private $metadataGroupDao;
	/**
	 * @var MetadataSetDao
	 */
	private $metadataSetDao;
	/**
	 * @var MetadataDao
	 */
	private $metadataDao;
	/**
	 * @var MetadataOptionDao
	 */
	private $metadataOptionDao;
	/**
	 * @var ColorDao
	 */
	private $colorDao;
	public function __construct() {
		parent::__construct ();
		$this->metadataGroupDao = new MetadataGroupDao ( );
		$this->metadataGroupDao->setDb ( $this->db );
		$this->metadataSetDao = new MetadataSetDao ( );
		$this->metadataSetDao->setDb ( $this->db );
		$this->metadataDao = new MetadataDao ( );
		$this->metadataDao->setDb ( $this->db );
		$this->metadataOptionDao = new MetadataOptionDao ( );
		$this->metadataOptionDao->setDb ( $this->db );
		
		$this->colorDao = new ColorDao ( );
		$this->colorDao->setDb ( $this->db );
	
	}
	
	public function getSets($view, $post) {
		$selectOptions = array ("0" => $this->_translate->translate ( 'noLabel' ), "1" => $this->_translate->translate ( 'yesLabel' ) );
		$dbGrid = new DBGrid ( $view );
		$dbGrid->setPost ( $post );
		$dbGrid->addFilter ( DBGridConstant::FILTER_TYPE_TEXT, "metadata_sets-title", $this->_translate->translate ( "title" ) );
		$dbGrid->addFilter ( DBGridConstant::FILTER_TYPE_TEXT, "metadata_sets-tag", $this->_translate->translate ( "tag" ) );
		//		$dbGrid->addOptionsFilter ( DBGridConstant::FILTER_TYPE_SELECT, "metadata_sets-default_cheque_rule", $this->_translate->translate ( "defaultChequeRule" ), MetadataConstant::getDefaultChequeRuleList () );
		//		$dbGrid->addOptionsFilter ( DBGridConstant::FILTER_TYPE_SELECT, "metadata_sets-default_price_rule", $this->_translate->translate ( "defaultPriceRule" ), MetadataConstant::getDefaultPriceRuleList () );
		//		$dbGrid->addOptionsFilter ( DBGridConstant::FILTER_TYPE_SELECT, "metadata_sets-default_ship_rule", $this->_translate->translate ( "defaultShipRule" ), MetadataConstant::getDefaultShipRuleList () );
		//		$dbGrid->addOptionsFilter ( DBGridConstant::FILTER_TYPE_SELECT, "metadata_sets-default_related_rule", $this->_translate->translate ( "defaultRelatedRule" ), MetadataConstant::getDefaultRelatedRuleList () );
		$dbGrid->addFetchTable ( "metadata_sets", "*" );
		$dbGrid->addValueFilter ( "metadata_sets-is_delete", "0" );
		$dbGrid->addFetchColumn ( "title", $this->_translate->translate ( "title" ), "edit" );
		$dbGrid->addFetchColumn ( "tag", $this->_translate->translate ( "tag" ) );
		$dbGrid->addFetchColumn ( "default_cheque_rule", $this->_translate->translate ( "defaultChequeRule" ), "", MetadataConstant::getDefaultChequeRuleList () );
		$dbGrid->addFetchColumn ( "default_price_rule", $this->_translate->translate ( "defaultPriceRule" ), "", MetadataConstant::getDefaultPriceRuleList () );
		$dbGrid->addFetchColumn ( "default_ship_rule", $this->_translate->translate ( "defaultShipRule" ), "", MetadataConstant::getDefaultShipRuleList () );
		$dbGrid->addFetchColumn ( "default_related_rule", $this->_translate->translate ( "defaultRelatedRule" ), "", MetadataConstant::getDefaultRelatedRuleList () );
		$dbGrid->setSortOrder("metadata_sets-title","ASC");
		//module action
		$dbGrid->addAAModuleAction ( "set", "add", $this->_translate->translate ( "addBtn" ), "add" );
		$dbGrid->setPageTitle ( $this->_translate->translate ( "metadataSetList" ) );
		$dbGrid->setModule ( '/metadata/set' );
		return $dbGrid->render ();
	}
	
	public function getSetById($id) {
		return $this->metadataSetDao->getSetById ( $id );
	}
	public function getGroupById($id) {
		return $this->metadataGroupDao->fetchRow ( 'id=' . $id );
	}
	
	public function getSetList() {
		return $this->metadataSetDao->fetchAll ( 'is_delete = 0' );
	}
	public function getSetMetadataBySetId($id) {
		return $this->metadataDao->getSetMetadataBySetId ( $id );
	}
	public function getSetMetaDatas($view, $post) {
		$selectOptions = array ("0" => $this->_translate->translate ( 'noLabel' ), "1" => $this->_translate->translate ( 'yesLabel' ) );
		$dbGrid = new DBGrid ( $view );
		$dbGrid->setPost ( $post );
		$dbGrid->addFilter ( DBGridConstant::FILTER_TYPE_TEXT, "metadats-code", $this->_translate->translate ( "code" ) );
		$dbGrid->addFilter ( DBGridConstant::FILTER_TYPE_TEXT, "metadats-title", $this->_translate->translate ( "title" ) );
		$dbGrid->addOptionsFilter ( DBGridConstant::FILTER_TYPE_SELECT, "metadats-input_type", $this->_translate->translate ( "inputType" ), MetadataConstant::getInputTypeList () );
		$dbGrid->addOptionsFilter ( DBGridConstant::FILTER_TYPE_SELECT, "metadats-in_basic_search", $this->_translate->translate ( "inBasicSearch" ), $selectOptions );
		$dbGrid->addOptionsFilter ( DBGridConstant::FILTER_TYPE_SELECT, "metadats-show_in_product", $this->_translate->translate ( "showInProduct" ), $selectOptions );
		$dbGrid->addFetchTable ( "metadatas", "*" );
		$dbGrid->addValueFilter ( "metadatas-is_delete", "0" );
		$dbGrid->addFetchColumn ( "title", $this->_translate->translate ( "title" ) );
		$dbGrid->addFetchColumn ( "long_title", $this->_translate->translate ( "longTitle" ) );
		$dbGrid->addFetchColumn ( "input_type", $this->_translate->translate ( "inputType" ), "", MetadataConstant::getInputTypeList () );
		$dbGrid->addFetchColumn ( "value_required", $this->_translate->translate ( "valueRequired" ), "", $selectOptions );
		$dbGrid->addFetchColumn ( "in_basic_search", $this->_translate->translate ( "inBasicSearch" ), "", $selectOptions );
		$dbGrid->addFetchColumn ( "show_in_product", $this->_translate->translate ( "showInProduct" ), "", $selectOptions );
		//module action
		//$dbGrid->addAAModuleAction("metadata","add",$this->_translate->translate("addBtn"),"add");
		$dbGrid->setPageTitle ( $this->_translate->translate ( "metadataList" ) );
		$dbGrid->setModule ( '/metadata/metadata' );
		$dbGrid->setReturnData ( true );
		$dbGrid->setCallBackMethod ( "MetadataSet.getReturn" );
		return $dbGrid->renderAjaxDbGrid ();
	
	}
	public function addSetDataById($setId) {
		$set = $this->getSetById ( $setId );
		$parentId = 0;
		$data = $set;
		unset ( $data ['id'] );
		$data ['title'] = $data ['title'] . '_' . time ();
		$newSetId = $this->addSetData ( $data );
		$groups = $this->metadataGroupDao->getGroupBySetId ( $setId );
		foreach ( $groups as $group ) {
			$data = $group;
			unset ( $data ['id'] );
			$data ['metadata_set_id'] = $newSetId;
			$newGroupId = $this->addGroupData ( $data );
			$metadatas = $this->metadataDao->getMetadataByGroupId ( $group ['id'] );
			foreach ( $metadatas as $metadata ) {
				$data = $metadata;
				unset ( $data ['id'] );
				$data ['group_id'] = $newGroupId;
				
				$data ['code'] = $data ['code'] . '_' . time ();
				$newMetadataId = $this->metadataDao->insertMetadata ( $data );
				$metadataOptions = $this->metadataOptionDao->getOptionsByMetadataId ( $metadata ['id'] );
				foreach ( $metadataOptions as $metadataOption ) {
					unset ( $metadataOption ['id'] );
					$metadataOption ['metadata_id'] = $newMetadataId;
					$this->metadataOptionDao->insertMetadataOption ( $metadataOption );
				}
			}
		}
		return $newSetId;
	}
	
	public function addSetData($data) {	    
		$result = $this->metadataSetDao->addSetData ( $data ); 	
		//insert log
        $log=new SystemLogService();
        $loginUser = BaseUtil::getLoginUser();
        $log->insertSystemLog('ADDSET',$loginUser['uname'], $data);	
        return $result;
	}
	public function addGroupData($data) {
		$result = $this->metadataGroupDao->insertData ( $data );
        //insert log
        $log=new SystemLogService();
        $loginUser = BaseUtil::getLoginUser();
        $log->insertSystemLog('ADDSGROUP',$loginUser['uname'], $data); 	
        return $result;	
	}
	public function updateSetData($data, $id) {
		$result = $this->metadataSetDao->updateData ( $data, 'id=' . $id );
        //insert log
        $log=new SystemLogService();
        $loginUser = BaseUtil::getLoginUser();
        $log->insertSystemLog('EDITSET',$loginUser['uname'], $data,$id); 
        return $result;		
	}
	public function updateGroupData($data, $id) {
		$result = $this->metadataGroupDao->updateData ( $data, 'id=' . $id );
        //insert log
        $log=new SystemLogService();
        $loginUser = BaseUtil::getLoginUser();
        $log->insertSystemLog('EDITSGROUP',$loginUser['uname'], $data,$id); 
        return $result; 		
	}
	public function addSetMetas($metadataIds, $setId) {
		foreach ( $metadataIds as $id ) {
			$data = array ('metadata_set_id' => $setId, 'metadata_id' => $id );
			$this->metadataDao->insertData ( $data );
		}
	}
	
	public function updateSetMetas($metadataIds, $setId) {
		foreach ( $metadataIds as $id ) {
			$row = $this->metadataDao->fetchRow ( 'metadata_set_id=' . $setId . ' and metadata_id=' . $id );
			if (empty ( $row )) {
				$data = array ('metadata_set_id' => $setId, 'metadata_id' => $id );
				$this->metadataDao->insertData ( $data );
			}
		}
		if (empty ( $metadataIds )) {
			$this->metadataDao->delete ( 'metadata_set_id=' . $setId );
		} else {
			$this->metadataDao->delete ( 'metadata_set_id=' . $setId . ' and metadata_id not in (' . implode ( ",", $metadataIds ) . ')' );
		}
	
	}
	
	public function deleteSetData($id) {
		$groups = $this->metadataGroupDao->getGroupBySetId ( $id );
		foreach ( $groups as $group ) {
			$this->deleteGroup ( $group ['id'] );
		}
		
		$this->metadataSetDao->updateData ( array ('is_delete' => 1 ), 'id=' . $id );
		//insert log
        $log=new SystemLogService();
        $loginUser = BaseUtil::getLoginUser();
        $log->insertSystemLog('DELSET',$loginUser['uname'],"", $id);
	
	}
	public function deleteGroup($id) {
		$metadatas = $this->metadataDao->getMetadataByGroupId ( $id );
		foreach ( $metadatas as $metadata ) {
			$this->deleteMetadata ( $metadata ['id'] );
		}
		$this->metadataGroupDao->updateData ( array ('is_delete' => 1 ), 'id=' . $id );
        //insert log
        $log=new SystemLogService();
        $loginUser = BaseUtil::getLoginUser();
        $log->insertSystemLog('DELSGROUP',$loginUser['uname'],"" ,$id);		
	}
	public function deleteMetadata($id) {
		//delete metadata option
		$metadataOption ['is_delete'] = 1;
		$this->metadataOptionDao->updateByMetadataId ( $metadataOption, $id );
		//delete metadata
		$metadata ['is_delete'] = 1;
		$this->metadataDao->updateData ( array ('is_delete' => 1 ), 'id=' . $id );
        //insert log
        $log=new SystemLogService();
        $loginUser = BaseUtil::getLoginUser();
        $log->insertSystemLog('DELMETA',$loginUser['uname'],"",$id);		
	}
	
	public function getSetTreeXml($setId) {
		$set = $this->getSetById ( $setId );
		$parentId = 0;
		
		$xml = '<tree id="0">';
		$xml .= '<item text="' . $set ['title'] . '" id="set_' . $set ['id'] . '" >';
		$groups = $this->metadataGroupDao->fetchAll ( "metadata_set_id = $setId and is_delete = 0", 'sort_order' );
		foreach ( $groups as $group ) {
			$xml .= '<item text="' . $group->title . '" id="group_' . $group->id . '" >';
			$metadatas = $this->metadataDao->fetchAll ( "group_id = {$group->id} and is_delete = 0", 'sort_order' );
			foreach ( $metadatas as $metadata ) {
				$xml .= '<item text="' . $metadata->title . '('. $metadata->id .')' . '" id="metadata_' . $metadata->id . '" >';
				$xml .= '</item>';
			}
			$xml .= '</item>';
		}
		//$xml .= $result;
		$xml .= '</item>';
		$xml .= '</tree>';
		return $xml;
	}
	
	public function saveMetadata($metadataForm, $post) {
		$metadata = array ();
		$optionValues = array ();
		$optionTitles = array ();
		$optionOrders = array ();
		$metadata ['code'] = $metadataForm->getValue ( "code" );
		$metadata ['group_id'] = str_replace ( 'group_', '', $post ["parentId"] );
		
		$metadata ['title'] = $metadataForm->getValue ( "title" );
		$metadata ['long_title'] = $metadataForm->getValue ( "longTitle" );
		$metadata ['input_type'] = $metadataForm->getValue ( "inputType" );
		$metadata ['value_required'] = $metadataForm->getValue ( "valueRequired" );
		$metadata ['in_basic_search'] = $metadataForm->getValue ( "inBasicSearch" );
		$metadata ['in_advanced_search'] = $metadataForm->getValue ( "inAdvanceSearch" );
		$metadata ['is_primary'] = $metadataForm->getValue ( "isPrimary" );
		$metadata ['show_in_product'] = $metadataForm->getValue ( "showInProduct" );
		$metadata ['type'] = $metadataForm->getValue ( "level" );
		$metadata ['sort_order'] = $metadataForm->getValue ( "sortOrder" );
		if ($metadata ['input_type'] == 1 || $metadata ['input_type'] == 2 || $metadata ['input_type'] == 5) {
			$metadata ['default_value'] = trim ( $post ['defaultValue'] );
		} else if ($metadata ['input_type'] == 3 || $metadata ['input_type'] == 4|| $metadata ['input_type'] == 6) {
			$optionValues = $post ['optionValue'];
			$optionTitles = $post ['optionTitle'];
			$optionOrders = $post ['optionOrder'];
		}
		$metadataId = $this->metadataDao->insertMetadata ( $metadata );
		if (! empty ( $optionValues )) {
			$i = 0;
			foreach ( $optionValues as $optionValue ) {
				$metadataOption = array ();
				$metadataOption ['metadata_id'] = $metadataId;
				$metadataOption ['value'] = trim ( $optionValue );
				$metadataOption ['title'] = trim ( $optionTitles [$i] );
				$metadataOption ['sort_order'] = trim ( $optionOrders [$i] );
				$this->metadataOptionDao->insertMetadataOption ( $metadataOption );
				$i ++;
			}
		}
        //insert log
        $log=new SystemLogService();
        $loginUser = BaseUtil::getLoginUser();
        $log->insertSystemLog('ADDMETA',$loginUser['uname'], $metadata); 		
	}
	
	public function getMetadata($id) {
		return $this->metadataDao->fetchRow ( 'id=' . $id )->toArray ();
	}
	public function getOptionsByMetadataId($metadataId) {
		$options = $this->metadataOptionDao->getOptionsByMetadataId ( $metadataId );
		return $options;
	}
	public function updateMetadata($metadataForm, $post) {
		$metadata = array ();
		$optionValues = array ();
		$optionTitles = array ();
		$optionOrders = array ();
		$deleteOptions = "";
		//update metadata
		$metadataId = $post ['id'];
		$inputType = $metadataForm->getValue ( "inputType" );
		$metadata ['code'] = $metadataForm->getValue ( "code" );
		$metadata ['title'] = $metadataForm->getValue ( "title" );
		$metadata ['long_title'] = $metadataForm->getValue ( "longTitle" );
		$metadata ['value_required'] = $metadataForm->getValue ( "valueRequired" );
		$metadata ['in_basic_search'] = $metadataForm->getValue ( "inBasicSearch" );
		$metadata ['in_advanced_search'] = $metadataForm->getValue ( "inAdvanceSearch" );
		$metadata ['is_primary'] = $metadataForm->getValue ( "isPrimary" );
		$metadata ['show_in_product'] = $metadataForm->getValue ( "showInProduct" );
		$metadata ['type'] = $metadataForm->getValue ( "level" );
		$metadata ['sort_order'] = $metadataForm->getValue ( "sortOrder" );
		if ($inputType == 1 || $inputType == 2 || $inputType == 5) {
			$metadata ['default_value'] = trim ( $post ['defaultValue'] );
		} else if ($inputType == 3 || $inputType == 4 || $inputType == 6) {
			$optionIds = $post ['optionId'];
 			$optionValues = $post ['optionValue'];
			$optionTitles = $post ['optionTitle'];
			$optionOrders = $post ['optionOrder'];
			$deleteOptions = $post['deleteOptionId'];
		}
		$this->metadataDao->updateMetadata ( $metadata, $metadataId );
		//update metadata option
		//delete option
		//$this->metadataOptionDao->deleteOption ( $metadataId );
		//insert new option
		if (! empty ( $optionValues )) {
			$i = 0;
			foreach ( $optionValues as $optionValue ) {
				$metadataOption = array ();
				$metadataOption ['metadata_id'] = $metadataId;
				$metadataOption ['value'] = trim ( $optionValue );
				$metadataOption ['title'] = trim ( $optionTitles [$i] );
				$metadataOption ['sort_order'] = trim ( $optionOrders [$i] );
				$metadataOptionId = $optionIds[$i];
				if($metadataOptionId == "0"){
					$this->metadataOptionDao->insertMetadataOption ( $metadataOption );
				}else{
					$this->metadataOptionDao->updateMetadataOption($metadataOption,$metadataOptionId);
				}
				$i ++;
			}
		}
		if(!empty($deleteOptions)){
			$this->metadataOptionDao->deleteOptionsById($deleteOptions);
		}
        //insert log
        $log=new SystemLogService();
        $loginUser = BaseUtil::getLoginUser();
        $log->insertSystemLog('EDITMETA',$loginUser['uname'], $metadata,$metadataId); 		
	}
	
	public function getMaxOrderOfGroup($setId) {
		$result = $this->metadataGroupDao->getMaxOrder ( $setId );
		$order = $result ['num'];
		return $order + 1;
	}
	public function getMaxOrderOfMetadata($id) {
		$result = $this->metadataDao->getMaxOrder ( $id );
		$order = $result ['num'];
		return $order + 1;
	}
	public function getColors(){
		return $this->colorDao->getColors();
	}
}